package com.example.coffeeseller_2.model.helper;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.utils.AssetUtil;
import com.example.coffeeseller_2.utils.DensityUtil;
import com.example.coffeeseller_2.utils.ObjectAnimatorUtil;
import com.example.coffeeseller_2.utils.Waiter;

import java.io.InputStream;

/**
 * Created by WH on 2018/8/12.
 * 口味支付页面的初动画处理类
 */

public class TradeAnimManager {

    private static String TAG = "TradeAnimManager";
    public static float IMAGE_SCALE = 0.85f;
    private Context context;
    private float screenWidht;
    private float screenHeight;
    private int leftMargin;
    private int topMargin;
    private int whiteHeight;//留白高度
    private int initWidth, initHeight;
    private OnAnimEndListener onAnimEndListener;
    Handler handler = new Handler();
    private int initTopMargin, initLeftMargin, initRightMargin, initBottomMargin, leftLength, rightLength, topLength, bottomLength, endRightMargin, endBottomMargin;

    public TradeAnimManager(Context context, OnAnimEndListener onAnimEndListener) {
        this.context = context;
        screenWidht = (float) DensityUtil.getScreenWidth(context);
        screenHeight = (float) DensityUtil.getScreenHeight(context);
        this.onAnimEndListener = onAnimEndListener;
    }

    public void initData(int leftMargin, int topMargin, boolean isHasTaste, int initWidth, int initHeight) {
        this.leftMargin = leftMargin;
        this.topMargin = topMargin;
        this.initWidth = initWidth;
        this.initHeight = initHeight;
        Log.d(TAG, "isHasTaste = " + isHasTaste);
        if (isHasTaste) {
            whiteHeight = (int) (screenHeight * 0.31);
        } else {
            whiteHeight = 0;
        }
        initLeftMargin = leftMargin;
        initTopMargin = topMargin;
        initRightMargin = (int) (screenWidht - leftMargin - initWidth);
        initBottomMargin = (int) (screenHeight - topMargin - initHeight);

        leftLength = leftMargin;
        rightLength = (int) (-screenWidht * 0.45 + initRightMargin);
        topLength = topMargin;
        bottomLength = -whiteHeight + initBottomMargin;

        endRightMargin = (int) (screenWidht * 0.45);
        endBottomMargin = whiteHeight;

    }

    public void showViewAnim(final View mContent, final ImageView mCropImage, final LinearLayout mFourthLayout,
                             final ImageView mTaijiImage, final LinearLayout mMaskLayout,
                             final LinearLayout mLeftInfoLayout, final LinearLayout mRightInfoLayout) {
        ObjectAnimator alphaAnimator = ObjectAnimatorUtil.alphaAnimator(mFourthLayout, 0f, 1f);
        alphaAnimator.setDuration(300);

        ObjectAnimator alphaAnimator1 = ObjectAnimatorUtil.alphaAnimator(mContent, 0.5f, 1f);
        alphaAnimator1.setDuration(300);
        //    alphaAnimator.start();

        //scaleAnim2(mContent, mCropImage, mFourthLayout);

        AnimatorSet set = new AnimatorSet();//.play(alphaAnimator)
        set.play(alphaAnimator1).with(scaleAndTrans(mCropImage)).with(alphaAnimator)
                .with(taijiAnim2(mTaijiImage)).with(alphaMaskLayout(mMaskLayout));
        //
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
//                mContent.setAlpha(1f);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        //  set.setStartDelay(200);
        set.start();

        alphaAnim(mLeftInfoLayout, mRightInfoLayout);
    }

    /*
    * 取杯码进入动画
    * */
    public void showViewAnimByQubeima(final View mContent, final ImageView mCropImage, final LinearLayout mFourthLayout,
                                      final ImageView mTaijiImage, final LinearLayout mMaskLayout,
                                      final LinearLayout mLeftInfoLayout, final LinearLayout mRightInfoLayout) {
        ObjectAnimator alphaAnimator = ObjectAnimatorUtil.alphaAnimator(mFourthLayout, 0f, 1f);
        alphaAnimator.setDuration(300);

        ObjectAnimator alphaAnimator1 = ObjectAnimatorUtil.alphaAnimator(mContent, 0.5f, 1f);
        alphaAnimator1.setDuration(300);


        AnimatorSet set = new AnimatorSet();
        set.play(alphaAnimator).with(alphaAnimator1)
                .with(taijiAnim2(mTaijiImage)).with(alphaMaskLayout(mMaskLayout));
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
//                mContent.setAlpha(1f);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        set.start();

        alphaAnim(mLeftInfoLayout, mRightInfoLayout);
    }


    /*
    * 进入动画
    * */
    public void enterAnim(final ImageView mCropImage, LinearLayout mFourthLayout, final ImageView mTaijiImage
            , final LinearLayout maskLayout, final LinearLayout mLeftInfoLayout, final LinearLayout mRightInfoLayout) {

//        scaleAndTransTask(mCropImage, initLeftMargin, initTopMargin, initRightMargin, initBottomMargin, leftLength, rightLength, topLength, bottomLength, time);
//        taijiAnim(mTaijiImage, maskLayout, mLeftInfoLayout, mRightInfoLayout);

   /*     scaleAndTrans(mCropImage);

        taijiAnim2(mTaijiImage);

        alphaMaskLayout(maskLayout);*/

        alphaAnim(mLeftInfoLayout, mRightInfoLayout);

    }

    /*
    * 线程方式实现移动缩放
    * */
    private void scaleAndTransTask(final ImageView mCropImage, final int initLeftMargin, final int initTopMargin, final int initRightMargin, final int initBottomMargin, final int leftLength, final int rightLength, final int topLength, final int bottomLength, final int time) {
        new AsyncTask<Void, Integer, Void>() {
            private int count = 0;
            private boolean isStop = false;
            private int index = 0;

            @Override
            protected Void doInBackground(Void... params) {


                while (!isStop) {

                    if (count > time) {

                        isStop = true;
                        break;
                    }

                    try {
                        Waiter.doWait(10);

                        int left = initLeftMargin - count * leftLength / time;
                        int right = initRightMargin + count * rightLength / time;
                        int top = initTopMargin - count * topLength / time;
                        int bottom = initBottomMargin + count * bottomLength / time;

                        if (left <= 0) {
                            left = 0;
                        }
                        if (right <= 0) {
                            right = 0;
                        }
                        if (top <= 0) {
                            top = 0;
                        }
                        if (bottom <= whiteHeight) {
                            bottom = whiteHeight;
                        }

                        count += 10;

                        publishProgress(left, top, right, bottom);

                        index += 1;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }


                return null;
            }

            @Override
            protected void onProgressUpdate(final Integer... values) {
                super.onProgressUpdate(values);
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        mCropImage.setPadding(values[0], values[1], values[2], values[3]);
                        mCropImage.requestLayout();
                        mCropImage.invalidate();
                    }
                });
            }
        }.execute();
    }

    /*
    * 动画方式移动
    * */
    private void scaleAnim(final View view, final LinearLayout mFourthLayout) {

        int durTime = 250;


        ValueAnimator animatorW = ValueAnimator.ofFloat(0, (1f - IMAGE_SCALE) / 2);//增长的倍数
        animatorW.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
               /* leftMargin = (int) (leftMargin - (value - IMAGE_SCALE) * initWidth / IMAGE_SCALE / 2);
                initRightMargin = (int) (initRightMargin - (value - IMAGE_SCALE) * initWidth / IMAGE_SCALE / 2);
                topMargin = (int) (topMargin - (value - IMAGE_SCALE) * initHeight / IMAGE_SCALE / 2);
                initBottomMargin = (int) (initBottomMargin - (value - IMAGE_SCALE) * initHeight / IMAGE_SCALE / 2);*/

                leftMargin = (int) (leftMargin - value * initWidth / IMAGE_SCALE);
                initRightMargin = (int) (initRightMargin - value * initWidth / IMAGE_SCALE);
                topMargin = (int) (topMargin - value * initHeight / IMAGE_SCALE);
                initBottomMargin = (int) (initBottomMargin - value * initHeight / IMAGE_SCALE);

                view.setPadding(leftMargin, topMargin, initRightMargin, initBottomMargin);
                view.requestLayout();
                view.invalidate();

            }
        });
        animatorW.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                initWidth = (int) (initWidth / IMAGE_SCALE);
                initHeight = (int) (initHeight / IMAGE_SCALE);
                leftLength = leftMargin;
                rightLength = (int) (-screenWidht * 0.45 + initRightMargin);
                topLength = topMargin;
                bottomLength = -whiteHeight + initBottomMargin;

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        ObjectAnimator alphaAnimator = ObjectAnimatorUtil.alphaAnimator(mFourthLayout, 0f, 1f);
        AnimatorSet set = new AnimatorSet();
        set.setDuration(durTime);
        set.playTogether(animatorW, alphaAnimator);
        set.start();
    }


    /*
   * 动画方式移动
   * */
    private void scaleAnim2(View content, final View view, final LinearLayout mFourthLayout) {
        ObjectAnimator alphaAnimator = ObjectAnimatorUtil.alphaAnimator(content, 0f, 1f);

        ObjectAnimator objectAnimator = ObjectAnimatorUtil.scaleAnimator(view, "X", IMAGE_SCALE, 1f);
        ObjectAnimator objectAnimator1 = ObjectAnimatorUtil.scaleAnimator(view, "Y", IMAGE_SCALE, 1f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(objectAnimator).with(objectAnimator1).with(alphaAnimator);
        animatorSet.setDuration(200);

        animatorSet.addListener(new Animator.AnimatorListener()

        {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {

                view.clearAnimation();


              /*  initWidth = (int) (initWidth / IMAGE_SCALE);
                initHeight = (int) (initHeight / IMAGE_SCALE);
                leftLength = leftMargin;
                rightLength = (int) (-screenWidht * 0.45 + initRightMargin);
                topLength = topMargin;
                bottomLength = -whiteHeight + initBottomMargin;*/

                initRightMargin = (int) (screenWidht - leftMargin - initWidth / IMAGE_SCALE);
                initBottomMargin = (int) (screenHeight - topMargin - initHeight / IMAGE_SCALE);


                initWidth = (int) (initWidth / IMAGE_SCALE);
                initHeight = (int) (initHeight / IMAGE_SCALE);
                leftLength = leftMargin;
                rightLength = (int) (-screenWidht * 0.45 + initRightMargin);
                topLength = topMargin;
                bottomLength = -whiteHeight + initBottomMargin;

                view.setPadding(leftMargin, topMargin, initRightMargin, initBottomMargin);
                view.requestLayout();
                view.invalidate();

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animatorSet.start();
    }


    /*
    * 动画方式移动
    * */

    private ValueAnimator scaleAndTrans(final View view) {

        int max1 = Math.max(leftLength, topLength);
        int max2 = Math.max(rightLength, bottomLength);

        int mode1 = leftLength > topLength ? 0 : 1;
        int mode2 = rightLength > bottomLength ? 2 : 3;

        final int mode = max1 > max2 ? mode1 : mode2;
        int startValue = 0;
        int endVaule = 0;
        if (mode == 0) {
            startValue = initLeftMargin;
            endVaule = 0;
        }
        if (mode == 1) {
            startValue = initTopMargin;
            endVaule = 0;
        }
        if (mode == 2) {
            startValue = initRightMargin;
            endVaule = (int) (screenWidht * 0.45);
        }
        if (mode == 3) {
            startValue = initBottomMargin;
            endVaule = whiteHeight;
        }

        int durTime = 500;


        ValueAnimator animatorL = ValueAnimator.ofFloat(startValue, endVaule);
        final int finalStartValue = startValue;
        final int finalEndVaule = endVaule;
        animatorL.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                float radio = ((finalStartValue - value) / (finalStartValue - finalEndVaule));
                if (mode == 0) {
                    float top = topMargin - topLength * radio;
                    top = top <= 0 ? 0 : top;
                    float right = initRightMargin - rightLength * radio;
                    right = right <= 0 ? 0 : right;
                    float bottom = initBottomMargin - bottomLength * radio;

                    view.setPadding((int) value, (int) top, (int) right, (int) bottom);
                    view.requestLayout();
                    view.invalidate();
                }

                if (mode == 1) {
                    float left = leftMargin - leftLength * radio;
                    left = left <= 0 ? 0 : left;
                    float right = initRightMargin - rightLength * radio;
                    right = right <= 0 ? 0 : right;
                    float bottom = initBottomMargin - bottomLength * radio;

                    view.setPadding((int) left, (int) value, (int) right, (int) bottom);
                    view.requestLayout();
                    view.invalidate();
                }

                if (mode == 2) {
                    float left = leftMargin - leftLength * radio;
                    left = left <= 0 ? 0 : left;
                    float top = topMargin - topLength * radio;
                    top = top <= 0 ? 0 : top;
                    float bottom = initBottomMargin - bottomLength * radio;

                    view.setPadding((int) left, (int) top, (int) value, (int) bottom);
                    view.requestLayout();
                    view.invalidate();
                }

                if (mode == 3) {
                    float left = leftMargin - leftLength * radio;
                    left = left <= 0 ? 0 : left;
                    float top = topMargin - topLength * radio;
                    top = top <= 0 ? 0 : top;
                    float right = initRightMargin - rightLength * radio;

                    view.setPadding((int) left, (int) top, (int) right, (int) value);
                    view.requestLayout();
                    view.invalidate();
                }


            }
        });
//        animatorL.setStartDelay(250);
        animatorL.setDuration(durTime);
//        animatorL.start();
        return animatorL;
    }


    private ValueAnimator taijiAnim2(final ImageView mTaijiImage) {

        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, ImageConstance.getSdBitmaps().length - 1);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();

                BitmapFactory.Options opt = new BitmapFactory.Options();
                opt.inPreferredConfig = Bitmap.Config.RGB_565;
                opt.inPurgeable = true;
                opt.inInputShareable = true;
                InputStream is = context.getResources().openRawResource(
                        ImageConstance.getSdBitmaps()[value]);
                Bitmap bm = BitmapFactory.decodeStream(is, null, opt);
                BitmapDrawable bd = new BitmapDrawable(context.getResources(), bm);
                mTaijiImage.setImageBitmap(bm);
//                mTaijiImage.setBackgroundDrawable(bd);

            }
        });
        valueAnimator.setDuration(500);
        return valueAnimator;

    }

    private ObjectAnimator alphaMaskLayout(LinearLayout maskLayout) {
        ObjectAnimator maskAnim = ObjectAnimatorUtil.alphaAnimator(maskLayout, 0f, 1f);
        maskAnim.setDuration(200);
        maskAnim.setStartDelay(300);
//        maskAnim.start();
        return maskAnim;

    }

    private void taijiAnim(final ImageView mTaijiImage, final LinearLayout maskLayout, final LinearLayout mLeftInfoLayout, final LinearLayout mRightInfoLayout) {
        if (ImageConstance.getSdBitmaps() != null && ImageConstance.getSdBitmaps().length > 0) {
            final float length = (screenHeight / ImageConstance.getSdBitmaps().length);
            final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, screenHeight);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    final float value = (Float) valueAnimator.getAnimatedValue();


                    if ((int) (value / length) < ImageConstance.getSdBitmaps().length) {

                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) value);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mTaijiImage.setImageResource(ImageConstance.getSdBitmaps()[(int) (value / length)]);

                            }
                        });
                    }

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            maskLayout.setAlpha(1 - (screenHeight - value) / (screenHeight / 4));

                        }
                    });

                }
            });
            valueAnimator.setDuration(700);
            valueAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mTaijiImage.setImageResource(ImageConstance.getSdBitmaps()[ImageConstance.getSdBitmaps().length - 1]);
                            alphaAnim(mLeftInfoLayout, mRightInfoLayout);

                        }
                    });

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            valueAnimator.start();
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.mask);
                    mTaijiImage.setImageBitmap(bitmap);
                    mTaijiImage.setAlpha(1f);
                }
            });

        }
    }


    /*
    * 信息显示动画
    * */
    private void alphaAnim(LinearLayout mLeftInfoLayout, LinearLayout mRightInfoLayout) {
        mLeftInfoLayout.setVisibility(View.VISIBLE);
        mRightInfoLayout.setVisibility(View.VISIBLE);
        ObjectAnimator leftAnim = ObjectAnimatorUtil.alphaAnimator(mLeftInfoLayout, 0f, 1f);
        ObjectAnimator rightAnim = ObjectAnimatorUtil.alphaAnimator(mRightInfoLayout, 0f, 1f);
        AnimatorSet set1 = new AnimatorSet();
        set1.setStartDelay(600);// + 250
        set1.setDuration(600);
        set1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (onAnimEndListener != null) {
                    onAnimEndListener.animEnd();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        set1.play(leftAnim).with(rightAnim);
        set1.start();
    }

    /*
    * 开启所有静态页面的旋转动画
    * */
    public static void startWaitRotateAnim(final View view, final int fromDegress, final int toDegress) {

        ValueAnimator an = ValueAnimator.ofFloat(fromDegress, toDegress);
        an.setDuration(10 * 1000);
        an.setRepeatCount(ValueAnimator.INFINITE);//或-1，一直循环
        an.setRepeatMode(ValueAnimator.RESTART);
        an.setInterpolator(new LinearInterpolator());
        an.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setRotation((Float) animation.getAnimatedValue());
            }
        });
        an.start();
    }


    public static void startMakingAnim(Context context, ImageView view, String path) {

        Log.d(TAG, "path= " + path);
        Glide.with(context)
                .load(AssetUtil.PATH_HEAD + path)
                .into(view);

    }


    public interface OnAnimEndListener {
        void animEnd();
    }
}
